package com.mcxx.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;



@Configuration
@EnableAsync
public class ListenerAsyncConfiguration implements AsyncConfigurer {
    private final static Logger logger = LoggerFactory.getLogger(ListenerAsyncConfiguration.class);
    @Autowired
    private AsyncPoolConfigProperties poolConfig;


    @Override
    @Bean("eventAsyncExecutor")
    public Executor getAsyncExecutor() {

        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();

        taskExecutor.setCorePoolSize(poolConfig.getCorePoolSize());
        taskExecutor.setMaxPoolSize(poolConfig.getMaxPoolSize());
        taskExecutor.setQueueCapacity(poolConfig.getQueueCapacity());
        taskExecutor.setKeepAliveSeconds(poolConfig.getKeepAliveSeconds());
        taskExecutor.setThreadNamePrefix(poolConfig.getThreadNamePrefix());
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (ex, method, params) -> {
            logger.error("==========================" + ex.getMessage() + "=======================", ex);
            logger.error("exception method:" + method.getName());
        };
    }
}
